<?php
/**
 * Locates the gallery image and encode it as base64 and en sends it
 * 
 * @author Sean
 * @return Base64 encoded image
 */
 
include ("connect.php");
include ("config.php");

$GoogleID = $_GET['googleId'];
$GoogleID = mysql_real_escape_string($GoogleID);

$SessionID = $_GET['sessionId'];
$SessionID = mysql_real_escape_string($SessionID);

$imageName = $_GET['imageName'];
$imageName = mysql_real_escape_string($imageName);


// Checks if the sessionid is valid
$result = mysql_query("SELECT sessionID FROM users WHERE GoogleID = '" . $GoogleID . "'");
while ($row = mysql_fetch_array($result)) {
   $DB_SessionID = $row["sessionID"];
}

if($SessionID == $DB_SessionID){

	$filePath =  $pathToUsersFiles.$GoogleID."/gallery/".$imageName;

	if (file_exists($filePath))
	{	
		$ext = end(explode('.', strtolower($imageName)));
		
		if($ext == "jpg" || $ext == "jpeg" || $ext == "png" || $ext == "gif"){
		// header("Content-type:image/jpeg");
			header('Access-Control-Allow-Origin: *');
			echo base64_encode_image($filePath,$ext);
		}
	}
	else{
		header('Access-Control-Allow-Origin: *');
		echo "ERROR: File does not exist.";
	}
}
else{
	header('Access-Control-Allow-Origin: *');
	header('Location: http://sean.servern.org/webdrop/Webdrop.html?#page=Login');
}

/**
 * Encode the image to a base64 and return it
 * 
 * @author Sean
 */
function base64_encode_image ($filename=string,$filetype=string) {
    if ($filename) {
        $imgbinary = fread(fopen($filename, "r"), filesize($filename));
        return 'data:image/' . $filetype . ';base64,' . base64_encode($imgbinary);
    }
}


?>